package net.zjitc.inter;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.zjitc.utils.APIResponse;
import net.zjitc.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminInterceptor extends HandlerInterceptorAdapter {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //Object admin = request.getSession().getAttribute("admin");
        String token = request.getHeader("jwt");

        //有---》判断token是否过期
        if(token!=null){
            //没有过期，放行
            Boolean flag = JwtUtil.isTokenExpired(token);
            if(flag){
                return true;
            }
        }


       //告诉前端，需要携带token
        APIResponse<String> apiResponse = new APIResponse<>();
        apiResponse.error(2,"用户过期或者还没有登录",null);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(apiResponse));
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
